package com.source.barcodeMachineGrantAndRecovery.controller;


import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.source.barcodeMachineGrantAndRecovery.VO.BarcodeMachineGrantVO;
import com.source.barcodeMachineGrantAndRecovery.entity.BarcodeMachineGrant;
import com.source.barcodeMachineGrantAndRecovery.entity.HouseMachineGrant;
import com.source.barcodeMachineGrantAndRecovery.service.BarcodeMachineGrantService;
import com.source.barcodeMachineGrantAndRecovery.service.HouseMachineGrantService;
import com.source.baseData.entity.BarcodeMachine;
import com.source.baseData.service.BarcodeMachineService;
import com.source.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 脚标机发放记录信息管理控制器
 * </p>
 *
 * @author Feng
 * @since 2021-02-24
 */

@Api(tags = "档口脚标机发放记录/总表信息管理 - 二级发放")
@RestController
@CrossOrigin
@RequestMapping("/barcode-machine-grant")
public class BarcodeMachineGrantController {

    @Autowired
    private HouseMachineGrantService grantService;

    @Autowired
    private BarcodeMachineService machineService;

    @Autowired
    private BarcodeMachineGrantService stallsGrantService;

    @Autowired
    private DateUtils dateUtils;

    @ApiOperation("给档口发放新的脚标机【新租期、租金等】")
    @PostMapping("/add")
    public CommonResult<String> add(@RequestBody @Validated BarcodeMachineGrant machineGrant) {
        try {

            //给这个记录设置id
            machineGrant.setGrantId(IdWorker.get32UUID());

            //更新屠宰市场（发放）表的最新状态，需要查找到处于真正发放状态下的id，因此调用去重接口查找list
            //直接根据脚标机编号查总表，再查对应number的houseGrantId
            BarcodeMachine byMachineNumber = machineService.findByMachineNumber(machineGrant.getBarcodeMachineNumber());

            //这里就可以拿到最新的、实际的屠宰市场发放表的脚标机【因为HouseGrantId相当于主键】
            HouseMachineGrant byId = grantService.getById(byMachineNumber.getHouseGrantId());
            //更新屠宰市场发放表的stallsGrantId
            byId.setStallsGrantId(machineGrant.getGrantId());
            byId.setStatus(1);
            if (machineGrant.getIsHired() == 1) {
                //如果是买的，就设置一个比较大的时间
                Date date1 = dateUtils.stringToDate("3021-12-31");
                machineGrant.setExpiringDate(date1);
                //如果是租的，前台会返回时间和状态码
            }
            
            //更新、保存进数据库
            if (stallsGrantService.save(machineGrant) && grantService.updateById(byId)) {
                return new CommonResult<String>(ResultEnum.SUCCESS);
            } else {
                return new CommonResult<String>(ResultEnum.ERROR);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常！");
        }
    }

    @ApiOperation("查找屠宰档口还没发放的脚标机 - 返回list集合")
    @GetMapping("/findUnGranted")
    public CommonResult<List<HouseMachineGrant>> findUnGranted() {
        List<HouseMachineGrant> list = grantService.findUnGranted();
        return new CommonResult<List<HouseMachineGrant>>(ResultEnum.SUCCESS, list);
    }

    @ApiOperation("更新档口发放记录")
    @PutMapping("/update")
    public CommonResult<String> update(@RequestBody BarcodeMachineGrant machineGrant) {
        try {
            if (stallsGrantService.updateById(machineGrant)) {
                return new CommonResult<String>(ResultEnum.SUCCESS);
            } else {
                return new CommonResult<String>(ResultEnum.ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常！");
        }
    }

    @ApiModelProperty("根据【主键id】删除档口脚标机")
    @DeleteMapping("/deleteById/{id}")
    public CommonResult<String> deleteById(@PathVariable String id) {
        try {
            BarcodeMachineGrant byId = stallsGrantService.getById(id);
            String barcodeMachineNumber = byId.getBarcodeMachineNumber();

            //这里已经处理成查询到最新的记录
            HouseMachineGrant byMachineNumber = grantService.findByMachineNumber(barcodeMachineNumber);

            if (stallsGrantService.removeById(id)) {

                //这里要判断移除的记录是不是和总表记录的一致！！
                if(byId.getGrantId().equals(byMachineNumber.getStallsGrantId())){
                    //从档口表删除之后，就是相当于不再发放给这个档口了
                    byMachineNumber.setStallsGrantId(null);
                    byMachineNumber.setStatus(0);
                    grantService.updateById(byMachineNumber);
                }
                //一致就需要更新屠宰市场发放表的GrantId，不然就不需要处理。
                return new CommonResult<String>(ResultEnum.SUCCESS);
            } else {
                return new CommonResult<String>(ResultEnum.ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常");
        }
    }

    @ApiOperation("根据【主键id】查找档口脚标机发放类")
    @GetMapping("/findById/{id}")
    public CommonResult<BarcodeMachineGrantVO> findById(@PathVariable String id) {
        BarcodeMachineGrantVO grantVO = stallsGrantService.findById(id);
        return new CommonResult<>(ResultEnum.SUCCESS, grantVO);
    }

    @ApiOperation("查找所有 - 分页")
    @GetMapping("/findAll/{current}/{size}")
    public CommonResult findAll(@PathVariable Integer current, @PathVariable Integer size) {

        List<BarcodeMachineGrantVO> list = stallsGrantService.findAll();
        Page page = MyPage.list2Page(current, size, list);
        return new CommonResult<>(ResultEnum.SUCCESS, page);
    }

    @ApiOperation("模糊查找 - 分页")
    @GetMapping("/findByLike/{current}/{size}/{keyWord}")
    public CommonResult findByLike(@PathVariable Integer current, @PathVariable Integer size, @PathVariable String keyWord) {
        List<BarcodeMachineGrantVO> list = stallsGrantService.findByLike(keyWord);
        Page page = MyPage.list2Page(current, size, list);
        return new CommonResult<>(ResultEnum.SUCCESS, page);
    }

    @ApiOperation("去重查找所有 - 分页")
    @GetMapping("/findAllDistinct/{current}/{size}")
    public CommonResult findAllDistinct(@PathVariable Integer current, @PathVariable Integer size) {

        List<BarcodeMachineGrantVO> list = stallsGrantService.findAllDistinct();
        Page page = MyPage.list2Page(current, size, list);
        return new CommonResult<>(ResultEnum.SUCCESS, page);
    }

    @ApiOperation("去重模糊查找 - 分页")
    @GetMapping("/findDistinctByLike/{current}/{size}/{keyWord}")
    public CommonResult findDistinctByLike(@PathVariable Integer current, @PathVariable Integer size, @PathVariable String keyWord) {
        List<BarcodeMachineGrantVO> list = stallsGrantService.findDistinctByLike(keyWord);
        Page page = MyPage.list2Page(current, size, list);
        return new CommonResult<>(ResultEnum.SUCCESS, page);
    }

//    @ApiOperation(value = "获取动态二维码标识,商户或市场管理员登录脚标机用")
//    @GetMapping("/getQR")
//    public CommonResult<String> viewQRCode(String barcodeMachineNumber) {
//
//        try {
//            String code = stallsGrantService.viewQRCode(barcodeMachineNumber);
//            if (!"error".equals(code)) {
//                return new CommonResult<String>(ResultEnum.SUCCESS, code);
//            } else {
//                return new CommonResult<String>(ResultEnum.ERROR, "无权限");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new CommonResult<String>(ResultEnum.ERROR);
//        }
//    }

    @ApiOperation(value = "判断角色并登录脚标机")
    @GetMapping("/getQR")
    public CommonResult<String> viewQRCode(String barcodeMachineNumber, String id) {

        try {
            String code = stallsGrantService.viewQRCode(barcodeMachineNumber, id);
            if (!"error".equals(code)) {
                return new CommonResult<String>(ResultEnum.SUCCESS, code);
            } else {
                return new CommonResult<String>(ResultEnum.ERROR, "获取失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR);
        }
    }


}

